<template>
  <div id="MyBookRecordPage" class="record-page">
    <!-- 搜索和筛选区域 -->
    <a-card class="search-card" :bordered="false">
      <a-form :model="searchParams" layout="inline" @finish="doSearch" class="search-form">
        <a-form-item label="图书名称" class="search-item">
          <a-input
            v-model:value="searchParams.record_bookname"
            placeholder="请输入图书名称"
            class="search-input"
            allow-clear
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="ISBN编号" class="search-item">
          <a-input
            v-model:value="searchParams.record_bookisbn"
            placeholder="请输入ISBN"
            class="search-input"
            allow-clear
          />
        </a-form-item>
        <a-form-item class="search-item">
          <a-button type="primary" html-type="submit" class="search-btn">
            <SearchOutlined />
            搜索
          </a-button>
          <a-button @click="resetSearch" class="reset-btn">
            <ReloadOutlined />
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格区域 -->
    <a-card class="table-card" :bordered="false">
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTableChange"
        :loading="loading"
        :scroll="{ x: 800 }"
        class="data-table"
      >
        <template #bodyCell="{ column, record }">
          <!-- 图书名称列 -->
          <template v-if="column.dataIndex === 'record_bookname'">
            <div class="book-info">
              <div class="book-name">{{ record.record_bookname }}</div>
            </div>
          </template>

          <!-- 状态列 -->
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="getStatusColor(record)" class="status-tag">
              {{ getStatusText(record) }}
            </a-tag>
          </template>

          <!-- 时间列格式化 -->
          <template v-if="column.dataIndex === 'record_borrowtime'">
            <div class="time-cell">
              <div class="time-value">{{ formatTime(record.record_borrowtime) }}</div>
              <div class="time-label">借阅时间</div>
            </div>
          </template>

          <template v-if="column.dataIndex === 'record_remandtime'">
            <div class="time-cell" :class="{ overdue: isOverdue(record) }">
              <div class="time-value">{{ formatTime(record.record_remandtime) }}</div>
              <div class="time-label">应还时间</div>
              <div v-if="isOverdue(record)" class="overdue-badge">已逾期</div>
            </div>
          </template>

          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <div class="action-buttons">
              <a-button
                type="primary"
                size="small"
                @click="doRenew(record.record_id)"
                class="renew-btn"
                :disabled="!canRenew(record)"
              >
                <ReloadOutlined />
                续借
              </a-button>
              <a-popconfirm
                title="确定要归还这本书吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="doRecordBook(record.record_id)"
              >
                <a-button
                  type="default"
                  size="small"
                  class="return-btn"
                  :disabled="!canReturn(record)"
                >
                  <CheckOutlined />
                  归还
                </a-button>
              </a-popconfirm>
            </div>
          </template>
        </template>

        <!-- 空状态 -->
        <template #emptyText>
          <div class="empty-state">
            <div class="empty-icon">
              <FileSearchOutlined />
            </div>
            <div class="empty-text">暂无借阅记录</div>
            <div class="empty-description">您还没有借阅过任何图书</div>
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import {
  deleteRecordUsingPost,
  editRecordUsingPost,
  listMyRecordVoByPageUsingPost,
} from '@/api/recordController'
import {
  CheckOutlined,
  FileSearchOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { computed, onMounted, reactive, ref } from 'vue'

// 列定义
const columns = [
  {
    title: '图书名称',
    dataIndex: 'record_bookname',
    key: 'record_bookname',
    width: 200,
    ellipsis: true,
  },
  {
    title: 'ISBN编号',
    dataIndex: 'record_bookisbn',
    key: 'record_bookisbn',
    width: 150,
  },
  {
    title: '借阅时间',
    dataIndex: 'record_borrowtime',
    key: 'record_borrowtime',
    width: 150,
    sorter: true,
  },
  {
    title: '归还时间',
    dataIndex: 'record_remandtime',
    key: 'record_remandtime',
    width: 150,
    sorter: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]

const dataList = ref([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.RecordQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条记录`,
    pageSizeOptions: ['10', '20', '50'],
  }
})

// 获取借阅列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await listMyRecordVoByPageUsingPost(searchParams)
    console.log('获取借阅历史列表', res)
    if (res.data.data && res.data.code === 0) {
      dataList.value = res.data.data.records
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('获取借阅列表失败:', error)
    message.error('获取借阅列表失败')
  } finally {
    loading.value = false
  }
}

// 切换表格页数
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  getUserList()
}

// 归还图书
const doRecordBook = async (id: number) => {
  try {
    const res = await deleteRecordUsingPost({ id })
    console.log('归还图书', res)
    if (res.data.code === 0 && res.data.data) {
      message.success('归还成功')
      getUserList()
    } else {
      message.error(res.data.message || '归还失败')
    }
  } catch (error) {
    console.error('归还图书失败:', error)
    message.error('归还失败')
  }
}

// 续借图书
const doRenew = async (id: number) => {
  try {
    const targetRecord = dataList.value.find((item) => item.record_id === id)
    // 续借参数
    const newRemandTime = dayjs(targetRecord.record_remandtime)
      .add(7, 'day') // 续借7天
      .format('YYYY-MM-DD HH:mm:ss')
    const renewParams = {
      record_remandtime: newRemandTime,
      record_id: id,
    }
    const res = await editRecordUsingPost(renewParams)
    console.log('续借图书', res)
    if (res.data.code === 0 && res.data.data) {
      message.success('续借成功')
      getUserList()
    } else {
      message.error(res.data.message || '续借失败')
    }
  } catch (error) {
    console.error('续借图书失败:', error)
    message.error('续借失败')
  }
}

// 搜索
const doSearch = () => {
  searchParams.current = 1
  console.log('搜索', searchParams)
  getUserList()
}

// 重置搜索
const resetSearch = () => {
  searchParams.record_bookname = ''
  searchParams.record_bookisbn = ''
  searchParams.current = 1
  getUserList()
}

// 时间格式化
const formatTime = (time: string) => {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取状态文本
const getStatusText = (record: any) => {
  const remandTime = dayjs(record.record_remandtime)
  const now = dayjs()

  if (remandTime.isBefore(now)) {
    return '已逾期'
  } else if (remandTime.diff(now, 'day') <= 3) {
    return '即将到期'
  } else {
    return '借阅中'
  }
}

// 获取状态颜色
const getStatusColor = (record: any) => {
  const status = getStatusText(record)
  switch (status) {
    case '已逾期':
      return 'error'
    case '即将到期':
      return 'warning'
    case '借阅中':
      return 'processing'
    default:
      return 'default'
  }
}

// 检查是否逾期
const isOverdue = (record: any) => {
  return dayjs(record.record_remandtime).isBefore(dayjs())
}

// 是否可以续借
const canRenew = (record: any) => {
  return !isOverdue(record)
}

// 是否可以归还
const canReturn = (record: any) => {
  return true // 这里可以根据实际业务逻辑调整
}

// 获取当前借阅数量
const getActiveCount = () => {
  return dataList.value.filter((record) => !isOverdue(record)).length
}

onMounted(() => {
  getUserList()
})
</script>

<style lang="scss" scoped>
.record-page {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

// 页面标题区域
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px 24px;
  margin-bottom: 24px;

  .header-content {
    margin-bottom: 24px;

    .page-title {
      font-size: 28px;
      font-weight: 700;
      margin: 0 0 8px 0;
      display: flex;
      align-items: center;

      .title-icon {
        margin-right: 12px;
        font-size: 24px;
      }
    }

    .page-subtitle {
      font-size: 16px;
      opacity: 0.9;
      margin: 0;
    }
  }

  .stats-cards {
    display: flex;
    gap: 16px;

    .stat-card {
      background: rgba(255, 255, 255, 0.15);
      backdrop-filter: blur(10px);
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      min-width: 180px;

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        margin-right: 16px;

        &.total {
          background: rgba(255, 255, 255, 0.2);
          color: #fff;
        }

        &.active {
          background: rgba(255, 255, 255, 0.2);
          color: #fff;
        }
      }

      .stat-info {
        .stat-number {
          font-size: 24px;
          font-weight: 700;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
          margin-top: 4px;
        }
      }
    }
  }
}

// 搜索卡片
.search-card {
  margin: 0 24px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .search-item {
      margin-bottom: 0;

      :deep(.ant-form-item-label) {
        font-weight: 500;
      }

      .search-input {
        width: 200px;
        border-radius: 8px;
      }
    }

    .search-btn {
      border-radius: 8px;
      height: 40px;
      padding: 0 20px;
    }

    .reset-btn {
      border-radius: 8px;
      height: 40px;
      padding: 0 20px;
      margin-left: 8px;
    }
  }
}

// 表格卡片
.table-card {
  margin: 0 24px 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;

  .data-table {
    :deep(.ant-table-thead > tr > th) {
      background: #f8fafc;
      font-weight: 600;
      color: #374151;
      border-bottom: 1px solid #e5e7eb;
    }

    :deep(.ant-table-tbody > tr > td) {
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.3s;
    }

    :deep(.ant-table-tbody > tr:hover > td) {
      background: #f8fafc;
    }
  }
}

// 表格内容样式
.book-info {
  .book-name {
    font-weight: 500;
    color: #1f2937;
  }
}

.status-tag {
  border: none;
  border-radius: 6px;
  font-weight: 500;
  padding: 4px 8px;
}

.time-cell {
  position: relative;

  .time-value {
    font-weight: 500;
    color: #1f2937;
  }

  .time-label {
    font-size: 12px;
    color: #6b7280;
    margin-top: 2px;
  }

  &.overdue {
    .time-value {
      color: #ef4444;
    }

    .overdue-badge {
      position: absolute;
      top: -8px;
      right: -8px;
      background: #ef4444;
      color: white;
      font-size: 10px;
      padding: 2px 6px;
      border-radius: 10px;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 8px;

  .renew-btn,
  .return-btn {
    border-radius: 6px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .renew-btn:disabled,
  .return-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

// 空状态样式
.empty-state {
  padding: 60px 0;
  text-align: center;

  .empty-icon {
    font-size: 64px;
    color: #d1d5db;
    margin-bottom: 16px;
  }

  .empty-text {
    font-size: 16px;
    color: #6b7280;
    margin-bottom: 8px;
  }

  .empty-description {
    font-size: 14px;
    color: #9ca3af;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    padding: 20px 16px;

    .stats-cards {
      flex-direction: column;

      .stat-card {
        min-width: auto;
      }
    }
  }

  .search-card,
  .table-card {
    margin: 0 16px 16px;
  }

  .search-form {
    flex-direction: column;

    .search-item {
      width: 100%;

      .search-input {
        width: 100% !important;
      }
    }
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>
